#' @title 箱型图示例 #boxplot #3-factors #aggregate
#' @description 使用模拟数据创建箱型图。支持输入长数据格式数据，支持1~3个因子变量。
#' @Eexample
#' aggr_boxplot(df, x = "condition", hue = "stimulus", dv = "rt")
#' aggr_boxplot(df, x = "condition", facet = c("stimulus"), dv = "rt")

load("simulated_data.rdata")
library(dplyr)
library(ggplot2)
library(see)

aggr_boxplot <- function(df, x, dv, hue=x, ylabs = dv, facets = c(), leg_pos = "right", subject_id="subject_id") {
  
  if(is.grouped_df(df)){
    aa = df
  }else{
    aa = df %>% 
      group_by( across( all_of(unique(c(x,hue,facets,subject_id))) )) %>% 
      summarise(!!sym(dv) := mean(!!sym(dv)), .groups = "keep")
  }
  
  if(is.vector(x)){
    n_vars = length(x)
    if(n_vars>1){
      hue = x[2]
      x = x[1]
    }
    if(n_vars>2){
      facets = x[-1:2]
    }
  }
  a1 = aa %>% ggpubr::ggboxplot(
    x = x,
    y = dv,
    color = hue,
    shape = hue,
    add = "jitter",
    add.params = list(alpha = 0.3),
    ylab = ylabs
  )
  if (length(facets) == 1) {
    facet.formula <- paste0("~", glue::backtick(facets)) %>% 
      stats::as.formula()
    a1 <- a1 + facet_wrap(facet.formula, labeller = labeller(.default = format_label) )
  }
  else if (length(facets) == 2) {
    facet.formula <- paste(glue::backtick(facets), collapse = " ~ ") %>% 
      stats::as.formula()
    a1 <- a1 + facet_grid(facet.formula, labeller = labeller(.default = format_label) )
  }
  
  a1 = a1 + 
    labs(x="", color="", fill="", shape="")+
    theme_modern() +
    theme(
      strip.text.x = element_text(size = 14),
      legend.position = leg_pos,
      legend.key.width= unit(0.5, 'cm'),
      legend.spacing = unit(0.1, 'cm'),
      legend.margin = margin(t = 0, r = 0, b = 5, l = 5),
      legend.box.spacing = unit(0.1, "cm")
    )
  a1
}

aggr_boxplot(
  df,
  x = "condition",
  hue = "stimulus",
  dv = "rt"
)
